import { Injectable } from '@angular/core';
import { HomePage } from '../../pages/home/home';
import { NavController } from 'ionic-angular';
import { ExtendsApp } from '../../app/app.component';
import { StorageProvider } from '../storage/storage';

/*
  Generated class for the GlobalsProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class GlobalsProvider {

  public urls = {
    login: "https://localhost/api/login",
    menuGet: "https://localhost/api/menu/get",
    intraCityDistributionQuery: "https://localhost/api/business/task/queryIntraCityDistributionTask",
    getIntraCityDistribution: "https://localhost/api/business/task/getIntraCityDistribution",
    myTask: "https://localhost/api/business/task/queryMyTask",
    enums: "https://localhost/api/public/enums",
    geoInfo: "https://localhost/api/map/geo/info",
    saveIntraCityDistribution: "https://localhost/api/business/task/saveIntraCityDistribution",
    newIntraCityDistribution: "https://localhost/api/business/task/createIntraCityDistribution",
    deleteIntraCityDistribution: "https://localhost/api/business/task/deleteIntraCityDistribution",
    publishIntraCityDistribution: "https://localhost/api/business/task/publishIntraCityDistribution",
    mapgetdistance: "https://localhost/api/map/getDistance"
  };

  public root: ExtendsApp;
  public authToken: string;
  public navControl: NavController;
  public messageHandlers = {
  };
  public ws: WebSocket;

  constructor(public store: StorageProvider) {
    try {
      let authToken = store.load("X-AUTH-TOKEN");
      if (authToken) {
        this.authToken = authToken;
      }
    } catch (e) {
      console.debug(e);
    }
    this.initWebSocket(this);
  }

  initWebSocket(me: GlobalsProvider) {
    me.ws = new WebSocket("wss://192.168.0.109/api/stream/socket");
    me.ws.onopen = () => {

    };
    me.ws.onmessage = (msg) => {
      for (let key in me.messageHandlers) {
        let handler = me.messageHandlers[key];
        handler(msg.data);
      }
    };
    me.ws.onerror = (err) => {
      me.initWebSocket(me);
    };
    me.ws.onclose = () => {
      me.initWebSocket(me);
    };
  }

  setWebSocketHandler(key: string, handler: any) {
    this.messageHandlers[key] = handler;
  }

}
